﻿using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using NOSDC.Entities;
using NOSDC.Pocos;

namespace NOSDC.Repositories.Documents
{
    public sealed class DocumentRepository : IDocumentRepository
    {
        private readonly NOSDCContext _db;

        public DocumentRepository()
        {
            _db = new NOSDCContext();
        }

        public void CreateDocument(Document doc)
        {
            _db.Documents.AddObject(doc);
            _db.SaveChanges();
        }

        public IEnumerable<Document> GetDocuments()
        {
            return _db.Documents.OrderByDescending(d => d.UploadDate);
        }

        public void DeleteDocument(Document doc)
        {
            _db.DeleteObject(doc);
            _db.SaveChanges();
        }

        public void UpdateDocument(Document doc)
        {
            _db.Documents.Attach(doc);
            var documentEntry = _db.ObjectStateManager.GetObjectStateEntry(doc);
            documentEntry.SetModified();
            _db.ObjectStateManager.ChangeObjectState(doc, System.Data.EntityState.Modified);
            _db.SaveChanges(SaveOptions.DetectChangesBeforeSave);
        }

        public Document GetDocumentById(int id)
        {
            return _db.Documents.FirstOrDefault(d => d.DocumentID == id);
        }
    }
}
